package com.hjw.rabbitmq.springbootorderrabbitmqproducer.service;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class orderService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void makeOrder(String userId, String productId,int num){
        //查询库存是否充足
        //保存订单
        String orderId= UUID.randomUUID().toString();
        //
        String exchangeName="topic_order_exchange";
        String routeKey="com.duanxin";
        rabbitTemplate.convertAndSend(exchangeName,routeKey,orderId);
    }


    //设置过期时间  消息 s后未被接受 过期
    public void makeOrderttlmessage(String userId, String productId,int num){
        //查询库存是否充足
        //保存订单
        String orderId= UUID.randomUUID().toString();
        //
        String exchangeName="ttl_direct_exchange";
        String routeKey="ttlmessage";

        // 将消息设置过期时间  （较少）  一般将队列设置过期时间
        MessagePostProcessor messagePostProcessor=new MessagePostProcessor(){
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setExpiration("5000");
                message.getMessageProperties().setContentEncoding("UTF-8");
                return message;
            }
        };

        rabbitTemplate.convertAndSend(exchangeName,routeKey,orderId);
    }
    //设置过期时间  消息 s后未被接受 过期
    public void makeOrderttl(String userId, String productId,int num){
        //查询库存是否充足
        //保存订单
        String orderId= UUID.randomUUID().toString();
        //
        String exchangeName="ttl_direct_exchange";
        String routeKey="ttl";

        // 将消息设置过期时间  （较少）  一般将队列设置过期时间
        MessagePostProcessor messagePostProcessor=new MessagePostProcessor(){
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setExpiration("5000");
                message.getMessageProperties().setContentEncoding("UTF-8");
                return message;
            }
        };

        rabbitTemplate.convertAndSend(exchangeName,routeKey,orderId);
    }
}
